package com.stylefeng.guns.modular.huamao.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.huamao.dao.SktAgentsStockholderMapper;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.huamao.dao.AgentsApplysMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * <p>
 * 代理公司股东申请表 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-04-17
 */
@Service
public class AgentsApplysServiceImpl extends ServiceImpl<AgentsApplysMapper, AgentsApplys> implements IAgentsApplysService {
	
	@Autowired
	private AgentsApplysMapper agentsApplysMapper;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private IUsersService iUsersService;
	@Autowired
	private ISktAgentsService iSktAgentsService;
	@Autowired
	private ISktAgentsAccountService sktAgentsAccountService;
	@Autowired
	private SktAgentsStockholderMapper sktAgentsStockholderMapper;

	@Autowired
	private ISktAgentsStockholderService sktAgentsStockholderService;
	@Override
	public List<AgentsApplysDTO> showDaiLiShenQingInfo(Page<AgentsApplysDTO>page,AgentsApplysDTO agentsApplysDTO) {
		List<AgentsApplysDTO> list = agentsApplysMapper.showDaiLiShenQingInfo(page,agentsApplysDTO);
		Integer total = agentsApplysMapper.showDaiLiShenQingInfoCount(agentsApplysDTO);
		page.setTotal(total);
		return list;
	}
	@Override
	public AgentsApplysDTO selectAddInfo(Integer shaId) {
		AgentsApplysDTO agentsApplysDTO = agentsApplysMapper.selectAddInfo(shaId);
		return agentsApplysDTO;
	}
	/**
	 * 查询前7个工作日申请代理通过
	 * @return
	 */
	@Override
	public List<AgentsApplys> getAgentsApplysSevenAgo(Integer userId){
		Map<String,Object> map=accountService.getSevenWorkDay();
		map.put("userId",userId);
		List<AgentsApplys> list = agentsApplysMapper.getAgentsApplysSevenAgo(map);
		return  list;
	}

	/**
	 * 确认代理申请
	 * @param shaId 股东申请表id
	 * @param staffId  操作员id
	 * @return
	 */
	@Override
	@Transactional
	public Map<String,Object> applysSetStatus(Integer shaId,Integer staffId){
		Map<String,Object> map=new HashMap();
		try{
			AgentsApplys agentsApplys = this.selectById(shaId);
			BigDecimal money = agentsApplys.getMoney();
			int userId = agentsApplys.getUserId();
			int agentId = agentsApplys.getAgentId();
			int type = agentsApplys.getType();
			//查询申请人
			Users users = iUsersService.selectById(userId);
			//申请人账户
			Account account=new Account();
			account.setUserId(userId);
			EntityWrapper<Account> entityWrapper=new EntityWrapper<Account>(account);
			Account account1 = accountService.selectOne(entityWrapper);
			//推荐人id
			int inviteId = users.getInviteId();
			//查询代理公司
			SktAgents sktAgents = iSktAgentsService.selectById(agentId);
			if (sktAgents==null){
				map.put("code","00");
				map.put("msg","该代理公司不存在");
				return  map;
			}
			//	Integer agencyFee = sktAgents.getAgencyFee();//每股缴纳代理费
			//判断是否是该公司股东
			SktAgentsStockholder sktAgentsStockholder3 =new SktAgentsStockholder();
			sktAgentsStockholder3.setAgentId(agentId);
			sktAgentsStockholder3.setUserId(userId);
			EntityWrapper<SktAgentsStockholder> ewr=new EntityWrapper<SktAgentsStockholder>(sktAgentsStockholder3);
			SktAgentsStockholder sktAgentsStockholder2 = sktAgentsStockholderService.selectOne(ewr);
			if(sktAgentsStockholder2!=null){
				map.put("code","00");
				map.put("msg","该用户已经是该公司股东，不能在申请该公司股东");
				return  map;
			}
			SktAgentsAccount agentsAccount=new SktAgentsAccount();//代理公司账号
			agentsAccount.setAgentId(agentId);
			EntityWrapper<SktAgentsAccount> wep=new EntityWrapper<SktAgentsAccount>(agentsAccount);
			SktAgentsAccount sktAgentsAccount = sktAgentsAccountService.selectOne(wep);
			//查询股东发展商家数量
			Integer countIsStore = iUsersService.selectCountIsStore (userId);
			Integer lPsurplusStockNum = sktAgents.getLPsurplusStockNum();
			Integer gPsurplusStockNum = sktAgents.getGPsurplusStockNum();
			//不同类型对应的股份数
			Integer stockNumTypeRe=0;
			if (type==7){
				if (lPsurplusStockNum==0){
					map.put("code","00");
					map.put("msg","该地区普通股东已满");
					return  map;
				}
				stockNumTypeRe=1;
				//修改代理公司表
				sktAgents.setLPsurplusStockNum(sktAgents.getLPsurplusStockNum()-1);
				sktAgents.setStockNum(sktAgents.getStockNum()+1);
				sktAgents.setStoreNum(sktAgents.getStoreNum()+countIsStore);
				iSktAgentsService.updateById(sktAgents);
				//修改申请表
				agentsApplys.setCheckRemark("二审通过");
				agentsApplys.setTwoCheckStaffId(staffId);
				agentsApplys.setTwoCheckTime(new Date());
				agentsApplys.setStatus(3);
				agentsApplys.setBatFlag(0);
				this.updateById(agentsApplys);
				//分红股东赠送上线双倍积分到积分账户
				//给上线发积分（经理或者代理）

				if (inviteId != 0) {
					Users inviteUsers = iUsersService.selectById (inviteId);
					//如果是主管申请代理判断下线7个工作日内是否有下线代理申请通过  如果有赠送双倍积分 begin
					if (users.getUserType() != 2) {
						//前七个工作日代理通过
						List<AgentsApplys> list = accountService.getAgentsApplysSevenAgo (userId);
						if (list != null && list.size() > 0) {
							BigDecimal sumScore = BigDecimal.ZERO;
							BigDecimal sumScoreFreeze = BigDecimal.ZERO;
							for (AgentsApplys AgentsApply : list) {
								sumScore = sumScore.add (AgentsApply.getMoney().multiply(new BigDecimal("200")));
							}
							if(sumScore.compareTo(BigDecimal.ZERO)==1){
								accountService.insertLogScore(userId, 10, agentsApplys.getOrderNo(), account1.getScore(), "被分享人升级为分红股东，赠送双倍积分到积分账户", sumScore, 1, userId);
								account1.setScore(account1.getScore().add (sumScore));
								account1.setTotalScore (account.getTotalScore().add(sumScore));
							}
//						am.updateById(account);
						}
					}
					//end
					//上线为股东或者经理赠送上线双倍积分 begin
					if (inviteUsers.getUserType() == 2 || inviteUsers.getIsAgent() != 0) {
						Account accountInvite = accountService.selectAccountByuserId(inviteId);
						BigDecimal doubelScore = money.multiply(new BigDecimal("200"));
						accountService.insertLogScore(userId, 10, agentsApplys.getOrderNo(), accountInvite.getScore(), "被分享人升级为分红股东，赠送双倍积分到积分账户", doubelScore, 1, inviteId);
						accountInvite.setScore (accountInvite.getScore().add(doubelScore));
						accountInvite.setTotalScore (accountInvite.getTotalScore().add(doubelScore));
						accountService.updateById(accountInvite);
					}
					//end
				}
			}
			if (type != 6 && type != 7) {
				SktAgentsStockholder agentsStockholder = new SktAgentsStockholder();
				agentsStockholder.setAgentId(agentId);
				agentsStockholder.setType(type);
				Integer countStcokManger = sktAgentsStockholderMapper.selectCountStcokManger(agentsStockholder);


				if (type == 1 ) {
					if (countStcokManger == 1){
						map.put("code","00");
						map.put("msg","董事长职位已满");
						return map;
					}
					stockNumTypeRe=5;
				} else if (type == 2  ) {
					if (countStcokManger == 1){
						map.put("code","00");
						map.put("msg","总裁职位已满");
						return map;
					}
					stockNumTypeRe=4;
				} else if (type == 3 ) {
					if (countStcokManger == 1){
						map.put("code","00");
						map.put("msg","行政职位已满");
						return map;
					}
					stockNumTypeRe=3;
				} else if (type == 4 ) {
					if (countStcokManger == 1){
						map.put("code","00");
						map.put("msg","财务职位已满");
						return map;
					}
					stockNumTypeRe=3;
				} else if (type == 5 ) {
					if (countStcokManger == 3){
						map.put("code","00");
						map.put("msg","部门经理职位已满");
						return map;
					}
					stockNumTypeRe=2;
				}
				sktAgents.setStockNum(sktAgents.getStockNum()+1);
				sktAgents.setStoreNum(sktAgents.getStoreNum()+countIsStore);
				sktAgents.setGPsurplusStockNum(sktAgents.getGPsurplusStockNum()-stockNumTypeRe);
				iSktAgentsService.updateById(sktAgents);
				//修改申请表
				agentsApplys.setCheckRemark("二审通过");
				agentsApplys.setTwoCheckStaffId(staffId);
				agentsApplys.setTwoCheckTime(new Date());
				agentsApplys.setStatus(3);
				agentsApplys.setBatFlag(1);
				Calendar c = Calendar.getInstance();
				c.setTime(new Date());//设置日历时间
				c.add(Calendar.MONTH, 3);//在日历的月份上增加3个月
				Date testTime=c.getTime();
				agentsApplys.setTestTime(testTime);
				this.updateById(agentsApplys);
//				insertLogScoreFreeze(0, 2, agentsApplys.getOrderNo(), account.getFreezeScore(), "升级代理", money.multiply(new BigDecimal("100")), 1, userId);
//				account.setFreezeScore(account.getFreezeScore().add(money.multiply(new BigDecimal("100"))));
//				am.updateById(account);
				//
			}
			//修改用户信息
			users.setIsAgent(type);
			iUsersService.updateById(users);
			//生成代理公司股东表
			SktAgentsStockholder agentsStockholder = new SktAgentsStockholder();
			agentsStockholder.setAgentId(agentId);
			agentsStockholder.setType(type);
			agentsStockholder.setCreateTime(new Date());
			agentsStockholder.setStockNum(stockNumTypeRe);
			agentsStockholder.setStoreNum(countIsStore);
			agentsStockholder.setUserId(userId);
			sktAgentsStockholderService.insert(agentsStockholder);
			//给本人发几份
			BigDecimal scoreAdd=money.multiply(new BigDecimal(100));//代理费所得积分
			//积分流水
			accountService.insertLogScore(0,9,agentsApplys.getOrderNo(),account1.getScore(),"升级代理公司股东，赠送积分到积分账户",scoreAdd,1,userId);
			account1.setScore(account1.getScore().add(scoreAdd));
			account1.setTotalScore(account1.getTotalScore().add(scoreAdd));
			accountService.updateById(account1);
			//判断代理公司账户是否开启 如果开启赠送到积分账户，关闭赠送到待发积分账户
			Integer runFlag=sktAgentsAccount.getRunFlag();
			if (runFlag==1){
				accountService.insertScoreAgent(1,agentId,agentsApplys.getOrderNo(),sktAgentsAccount.getScore(),1,scoreAdd,"代理通过，代理公司获得");
				sktAgentsAccount.setScore(sktAgentsAccount.getScore().add(scoreAdd));
				sktAgentsAccount.setTotalScore(sktAgentsAccount.getTotalScore().add(scoreAdd));
				sktAgentsAccountService.updateById(sktAgentsAccount);
			}else{
				//accountService.insertScoreAgent(0,9,transferAgentChenge.getChangeNo(),sktAgentsAccount.getScore(),"代理升级，代理公司获得",scoreAdd,1,userId);
				accountService.insertScoreAgent(2,agentId,agentsApplys.getOrderNo(),sktAgentsAccount.getFreezeScore(),1,scoreAdd,"代理通过，代理公司获得待发积分");
				sktAgentsAccount.setFreezeScore(sktAgentsAccount.getFreezeScore().add(scoreAdd));
				sktAgentsAccountService.updateById(sktAgentsAccount);
			}
			//检查开启代理公司运营账号货分红账号
			Map<String, Object> map1 =sktAgentsStockholderService.checkRunOrProfit(agentId, agentsApplys.getOrderNo());
			if ("00".equals(map1.get("code").toString())){
				return map1;
			}
			map.put("code","01");
			map.put("msg","操作成功");
		}catch (Exception e){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			map.put("code","00");
			map.put("msg","操作失败");
		}
		return  map;
	}
}
